﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.ProcurementsCommand;
using Yitter.IdGenerator;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.ProcurementsCommandCommand
{
    /// <summary>
    /// 采购到货添加方法
    /// </summary>
    public class AddPurchaseArrivalCommandHandler : IRequestHandler<AddPurcArrivalCommand, APIResult<object>>
    {

        /// <summary>
        /// 采购到货表
        /// </summary>
        private readonly IBaseRepository<PurchaseArrival> baseRepository;


        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository"></param>
        /// <param name="mapper"></param>
        public AddPurchaseArrivalCommandHandler(IBaseRepository<PurchaseArrival> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<object>> Handle(AddPurcArrivalCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.添加成功;
            result.Msg =APIEnum.添加成功.ToString();

            var list = mapper.Map<PurchaseArrival>(request);
            list.DocumentCode =YitIdHelper.NextId().ToString(); 
            int r = baseRepository.Add(list).Result;
            if (r > 0)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                result.data = r;
            }
            else
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }

            return Task.FromResult(result);
        }
    }
}
